// Purpose: Debug and unit test functions
//
// Created: Daly 2012-04-01

#include "ax_common.h"

static char _g_log_path[1024] = ".";
static int _g_debug_enable = 1;

#define DBG_LOGNAME "debug.log"
#define UTEST_LOGNAME "utest.log"

//our assertion wrapper
void ax_assert(const char *expr, const char* file, const char* func, int line)
{
	ax_debug("Assert:%s; file:%s func:%s line:%d", expr, file, func, line);
	abort();
}

//get formmated date
//@param  n  the max n bytes of buf
void ax_format_time(char* buf, int n)
{
	time_t timep ;
	struct tm *tp;
	time(&timep);
	tp = localtime(&timep);
	strftime(buf, n, "%Y/%m/%d-%H:%M:%S", tp);
}

//common va_args logger
void ax_vlogf(const char* file, const char* fmt, va_list arg)
{
	FILE *fp = NULL;
	static char path_buf[1048];
	static char timebuf[32];
	snprintf(path_buf, sizeof(path_buf), "%s/%s", _g_log_path, file);
	fp = fopen(path_buf, "a+");
    if (NULL == fp) {
        perror(path_buf);
        abort();
    }

	ax_format_time(timebuf, 32);	
    //write head info first
    fprintf(fp, "%s ", timebuf);
    vfprintf(fp, fmt, arg);
	fprintf(fp, "\n");
    fflush(fp);
}

void ax_logfile(const char* file, const char* fmt, ...)
{
	va_list args;
	va_start(args, fmt);
	ax_vlogf(file, fmt, args);
	va_end(args);
}

//debug log
void ax_debug(const char *fmt, ...)
{
	va_list args;
	if (!_g_debug_enable) return;
	va_start(args, fmt);
	ax_vlogf(DBG_LOGNAME, fmt, args);
	va_end(args);
}

void ax_utest_log(const char *fmt, ...)
{
	va_list args;
	if (!_g_debug_enable) return;
	va_start(args, fmt);
	ax_vlogf(UTEST_LOGNAME, fmt, args);
	va_end(args);
}

//set log path
void set_log_path(const char* path)
{
	strcpy(_g_log_path, path);
}

//enable or disable debug_log
//@param enable   0 for disable, 1 for enable
void switch_debug_log(int enable)
{
	_g_debug_enable = enable;
}

